/*
 * Copyright 2007 Jeffrey Palm.
 */

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import com.jeffpalm.bin.*;
import com.jeffpalm.util.*;

import com.sun.syndication.feed.synd.*;

public class ipodfork {

  private void note(Object msg) {
    Util.note(this,msg);
  }

  private void runFinder(Finder finder, ProgressImpl p, JFrame f) {
    try {
      if (finder instanceof ITunesFinder) {
        findNotes((ITunesFinder)finder,p,f);
      } else if (finder instanceof IPodFinder) {
        findNotesIPod((IPodFinder)finder,p,f);
      } else {
        findFeeds((RSSCollectionFinder)finder,p,f);
      }
    } catch (Exception ee) {Util.handle(this,ee);}
  }

  void realMain(String[] args) {

    final JFrame f = new JFrame();
    f.getContentPane().setLayout(new BoxLayout(f.getContentPane(),BoxLayout.Y_AXIS));
    Vector finders = new Vector();
    finders.add(new NYTimes());
    finders.add(new BloglinesFinder());
    finders.add(new Pitchfork());
    finders.add(new MapquestDirections());
    f.getContentPane().add(new JLabel("Please choose a finder..."));
    for (Iterator it = finders.iterator(); it.hasNext();) {
     final Finder finder = (Finder)it.next();
      f.getContentPane().add(new JButton(new AbstractAction(finder.name()) {
          public void actionPerformed(ActionEvent e) {
            new Thread(new Runnable() {
                public void run() {
                  final ProgressFrame pf = openFrame();
                  runFinder(finder,pf.p,f);
                }}).start();
          }
        }));
    }
    
    f.pack();    
    CenterHelper.center(f);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  private ProgressFrame openFrame() {
    ProgressFrame f = new ProgressFrame();
    f.pack();    
    CenterHelper.center(f);
    f.setVisible(true);
    return f;
  }


  private void findNotes(ITunesFinder finder, ProgressImpl p, JFrame f) throws Exception {
    p.setFinder(finder);
    p.update(finder.name() + "...",1);
    finder.find(new ITunes(),p);
  }

  private void findNotesIPod(IPodFinder finder, ProgressImpl p, JFrame f) throws Exception {
    p.setFinder(finder);
    p.update(finder.name() + "...",1);
    finder.find(new IPod(),p);
  }

  private void findFeeds(RSSCollectionFinder finder, ProgressImpl p, JFrame f) {

    // find the fuckers
    List feeds = new ArrayList();
    p.reset();
    note("using finder " + finder);
    try {
      p.setFinder(finder);
      p.inc();
      p.update("searching ...",0);
      RSSCollection lst = finder.getCollection(p);
      SyndFeed[] fs = lst.getFeeds();
      if (fs != null) {
        for (int i=0; i<fs.length; i++) {
          SyndFeed feed = fs[i];
          if (feed != null) feeds.add(feed);
        }
      }
      note("found " + (fs==null ? 0 : fs.length));
      p.inc();
    } catch (Exception e) {handle(e);}

    note("found " + feeds.size() + " feed(s)");
    p.reset();
    p.setMax(feeds.size());

    // Find the ipod
    final IPod ipod = new IPod();

    while (ipod.getRoot() == null) {
      int res = JOptionPane.showConfirmDialog(null,
                                              "Please plug in your iPod",
                                              "Plug in",
                                              JOptionPane.OK_CANCEL_OPTION);
      if (res == JOptionPane.CANCEL_OPTION) return;
    }

    note("ipod:"+ipod);
    p.update("found ipod",0);

    // add all the feeds
    File feedsDir = new File(ipod.getNotes(),finder.name());
    try {feedsDir.delete();} catch (Exception e) {e.printStackTrace();}
    feedsDir.mkdirs();
    if (feedsDir.exists()) doDelete(feedsDir);
    feedsDir.mkdirs();
    p.inc();
    for (Iterator it = feeds.iterator(); it.hasNext();) {
      SyndFeed feed = (SyndFeed)it.next();
      note("adding " + feed);
      String title = feed.getTitle();
      File feedDir = new File(feedsDir,title);
      doDelete(feedDir);
      feedDir.mkdirs();
      List es = feed.getEntries();
      for (Iterator jt = es.iterator(); jt.hasNext();) {
        SyndEntry e = (SyndEntry)jt.next();
        String t = e.getTitle();
        List cs = e.getContents();
        try {
          File outfile = new File(feedDir,t);
          p.update("Writing " + t,1);
          PrintStream out = new PrintStream(new FileOutputStream(outfile));
          out.println(e.getTitle());
          out.println(e.getPublishedDate());
          out.println("--");          
          for (Iterator kt = es.iterator(); kt.hasNext();) {
            Object o = kt.next();
            SyndEntry c = (SyndEntry)o;
            SyndContent content = c.getDescription();
            out.println(content.getValue());
          }
          out.close();
        } catch (Exception ee) {handle(ee);}
      }
    }

    // clean up
    f.setVisible(false);
    f.dispose();
 
    // show confirmation
    JOptionPane.showMessageDialog(null,"Updated");

    // exit
    System.exit(0);
  }

  private void handle(Exception e) {
    e.printStackTrace();
  }


  private void doDelete(File f) {
    if (f.isDirectory()) {
      File[] fs = f.listFiles();
      for (int i=0; i<fs.length; i++) doDelete(fs[i]);
    }
    f.delete();
  }

  public static void main(String[] args) {
    new ipodfork().realMain(args);
  }

}